import os
import xml.etree.ElementTree as ET
from loguru import logger


def replace_xml(jmx_file, num):
    # jmx_file = "order_auto.jmx"
    doc = ET.parse(jmx_file)
    root = doc.getroot()
    sub = root.find(".//stringProp[@name='ThreadGroup.num_threads']")
    sub.text = str(num)
    doc.write(jmx_file, encoding="utf-8", xml_declaration=True)


jmx_template = "order_auto"
suffix = ".jmx"
jmx_template_filename = jmx_template + suffix

thread_num = [20]
logger.info("开始自动化压测")
for num in thread_num:
    logger.info(f"设置线程数为：{num}")
    replace_xml("order_auto.jmx", num)
    jmx_filename = jmx_template + "_" + str(num) + suffix
    jtl_filename = f"test_{num}.jtl"
    web_report_path_name = f"web_{num}"
    os.system(f"rm -f {jmx_filename} {jtl_filename}")
    os.system(f"rm -rf {web_report_path_name}")
    os.system(f"cp -r -f {jmx_template_filename} {jmx_filename}")
    logger.info(f"生成jmx压测脚本 {jmx_filename}")

    os.system(f"jmeter -n -t {jmx_filename} -l {jtl_filename}")
    logger.info(f"生成压jtl文件 {jtl_filename}")

    os.system(f"jmeter -g {jtl_filename} -e -o {web_report_path_name}")
    logger.info("生成压测报告")
